﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Threading;
using System.Windows.Forms;

namespace LiteNote
{
    static class Program
    {
        /*const string dllPath = "user32.dll";
        [DllImport(dllPath, CharSet = CharSet.Auto, SetLastError = true)]
        private static extern int EnumWindows(CallBack x);

        delegate bool CallBack(IntPtr hwnd, int lParam);
        static IntPtr hWnd;
        static bool Report(IntPtr hwnd, int lParam)
        {
            string text = Utility.GetFormText(hwnd);
            if (text == "LiteNote") {
                hWnd = hwnd;
                return false;
            } else {
                hwnd = (IntPtr)0;
            }
            return true;
        }
        static CallBack myCallBack = Report;
        */

        static IntPtr formHandle;
        static string PipeName = "LiteNote_PipeName";

        static void ThreadBk()
        {
            try {
                while (true) {
                    using (NamedPipeServerStream pipeServer = new NamedPipeServerStream(PipeName, PipeDirection.InOut, 1)) {

                        pipeServer.WaitForConnection();
                        pipeServer.ReadMode = PipeTransmissionMode.Byte;

                        using (StreamWriter sw = new StreamWriter(pipeServer)) {
                            sw.WriteLine("server start");
                            Utility.ShowWindow(formHandle, 1);
                            Utility.SetForegroundWindow(formHandle);
                        }

                    }
                }
            } catch (IOException e) {
                throw e;
            }
        }

        static bool HaveRunning()
        {
            try {
                using (NamedPipeClientStream pipeClient = new NamedPipeClientStream("localhost", PipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None)) {

                    pipeClient.Connect(1);
                    using (StreamReader sr = new StreamReader(pipeClient)) {
                        string s = sr.ReadLine();
                        Console.WriteLine(s);
                    }
                }
            } catch (Exception ex) {
                Console.WriteLine("no server");
                // 如果连接失败, 则表示没有服务,也就是没有进程在运行
                return false;
            }

            return true;
        }


        [STAThread]
        static void Main()
        {
            // dep: 更高级的方式是用个全局的通信机制，而不是用窗口名查找
            /*EnumWindows(myCallBack);

            if (hWnd != (IntPtr)0) {
                Utility.ShowWindow(hWnd, 1);
                Utility.SetForegroundWindow(hWnd);
                return;
            }*/


            // TODO: 在linux下好像就不能这样做了
            if (HaveRunning())
                return;

            Thread thread = new Thread(new ThreadStart(ThreadBk));
            thread.IsBackground = true;
            thread.Start();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            NoteForm frm = new NoteForm();
            formHandle = frm.Handle;
            Application.Run(frm);
            //FrmMain frm = new FrmMain();
            //frm.Show();
        }
    }
}
